use std::fs::File;
use std::io::{self, prelude::*, BufReader};

fn main() -> io::Result<()>{
    let input = File::open("input.txt")?;
    let mut stack = Vec::new();
    let reader = BufReader::new(input);

    for line in reader.lines() {
        let str = line?;
        stack.push(str.parse::<i32>().unwrap());
    }

    stack.sort_unstable();
    let mut part_1_done = false;
    let mut part_2_done = false;
    let target_number = 2020;

    'main_loop: while let Some(first) = stack.pop(){
        let mut second_stack = stack.to_vec();
        while let Some(second) = second_stack.pop() {
            if first + second == target_number {
                println!("Part 1 answer is {} * {} = {}", first, second, first * second);
                part_1_done = true;
            }else if first + second > 2020 && part_2_done {
                break;
            }
            if !part_2_done {
                for third in &stack {
                    if first + second + third == target_number{
                        println!("Part 2 answer is {} * {} * {} = {}", first, second, third, first * second * third);
                        part_2_done = true;
                    }else if first + second < 2020 {
                        continue;            
                    }
                    break;
                }
            }
            if part_1_done && part_2_done {break 'main_loop;}
        }
    }
    if !part_1_done {println!("No answer found for part 1!")}
    if !part_2_done {println!("No answer found for part 2!")}

    Ok(())
}
